from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel

from database.database import engine
from sqlalchemy import text

from utils.access_token import create_access_token

import hashlib
import json

class LoginItem(BaseModel):
    username:str
    password:str


router = APIRouter(
    prefix='',
    tags = ['用户登录']
)

def user_login(username, password):
    # try:
    with engine.connect() as conn:
        sql = text(f'''
        select id, username, fullname, avatar, rolename, gender, mobile, mailaddr from ai_labs_user where username = :username and userpass = :userpass;
        ''')
        result = conn.execute(sql, [{'username': username, 'userpass': password}]).fetchone()
    return result
    # except:
    #   pass

@router.post("/login")
async def login(item:LoginItem):
    result = user_login(item.username, hashlib.md5(item.password.encode('utf-8')).hexdigest())
    if result:
        result_dict = result._asdict()
        result_dict["token"] = create_access_token({"id": result_dict["id"], "username": result_dict["username"], "rolename": result_dict["rolename"]})
        data = { "code": 0, "message": "操作成功" }
        data["data"] = result_dict
        return JSONResponse(status_code=200, content=data)
    else:
        data = { "code": 500, "message": "账号或密码错误" }
        return JSONResponse(status_code=200, content=data)
